<template>
  <div class="search">
    <Header v-py="10" class="header">
      <div class="header-center" slot="center">
        <div class="pic">
          <i class="icon icon-search"></i>
        </div>
        <input type="text" v-model="keyword" placeholder="雅马哈吉他">
      </div>
      <div @click="search" class="header-right" slot="right">
        搜索
      </div>
    </Header>
    <div class="main" v-m>
      <div class="history" v-if="historySearchs.length>0">
        <div class="title">
          <h2>历史搜索</h2>
          <div @click="resetHistory" class="pic">
            <i class="icon icon-del"></i>
          </div>
        </div>
        <div class="list">
          <router-link v-for="(item,index) in historySearchs" :to="`/list?keyword=${encodeURI(item)}`" :key="index" class="item">
            {{item}}
          </router-link>
        </div>
      </div>
      <div class="history" v-if="hots.length>0">
        <div class="title">
          <h2>搜索发现</h2>
        </div>
        <div class="list">
          <router-link v-for="(item,index) in hots" :to="`/list?keyword=${encodeURI(item)}`" :key="index" class="item">
            {{item}}
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Header from "../components/Header.vue";
import { setItem, getItem, removeItem } from "../helper/database.js";
import { isEmpty, uniq } from "lodash";
export default {
  name: "Search",
  components: {
    Header
  },
  data() {
    return {
      keyword: "",
      historySearchs: getItem("historySearchs") || [],
      hots: ["珠江教学钢琴", "小号", "日芬"]
    };
  },
  watch: {
    historySearchs: {
      deep: true,
      handler(newVal) {
        setItem("historySearchs", uniq(newVal));
      }
    }
  },
  methods: {
    search() {
      if (isEmpty(this.keyword)) {
        alert("搜索的东西不能为空");
        return;
      }
      this.historySearchs.push(this.keyword);
      this.$nextTick(() => {
        this.$router.push(`/list?keyword=${encodeURI(this.keyword)}`);
      });
    },
    resetHistory() {
      const result = confirm("是否要清空历史记录？");
      if (result) {
        removeItem("historySerchs");
        this.historySearchs = [];
      }
    }
  }
};
</script>
